import store from '../store'

let socket = null
const wsUrl = 'ws://127.0.0.1:14445/websocket'
const copyWsUrl = 'ws://127.0.0.1:13225/websocket'

const getData = (data) => {
  if (data && data.MethonId && data.Code === '40001') {
    store.dispatch('loading/hideLoading')
    store.dispatch('message/SetMsgInfo', {
      type: 'success',
      msg: '上传成功'
    })
  } else if (data && data.Code === '40001' && !data.MethonId) {
    store.dispatch('loading/showLoading')
  } else if (data && data.Code === '40002') {
    store.dispatch('loading/hideLoading')
    store.dispatch('message/SetMsgInfo', {
      type: 'error',
      msg: '上传失败'
    })
  } else {
    store.dispatch('loading/hideLoading')
  }
}

export const init = (url) => {
  if (typeof (WebSocket) === 'undefined') {
    alert('您的浏览器不支持WebSocket')
  } else {
    // 实例化socket
    socket = new WebSocket(url || wsUrl)
    // 监听socket连接
    socket.onopen = () => {
      // store.dispatch('settings/setMac')
      console.info('WebSocket连接成功')
    }
    // 监听socket错误信息
    socket.onerror = () => {
      console.error('WebSocket连接发生错误')
      !url && init(copyWsUrl)
    }
    // 监听socket消息
    socket.onmessage = (event) => {
      if (event.data === 'logout') {
        store.dispatch('user/logout').then(_ => {
          socket.send(JSON.stringify({ MethonId: '8' }))
        })
      } else {
        getData(JSON.parse(event.data))
      }
    }
    // 监听关闭事件
    socket.onclose = () => {
      console.info('WebSocket连接关闭')
    }
  }
}

export const send = (data) => {
  // 连接状态：0-CONNECTING 1-OPEN 2-CLOSING 3-CLOSED
  const state = socket.readyState

  switch (state) {
    case 1: {
      if (data.type && data.type === 'upload') {
        socket && socket.send(data.file)
      } else {
        socket && socket.send(JSON.stringify(data))
      }
      break
    }
    case 2:
    case 3: {
      init()
      setTimeout(() => {
        if (data.type && data.type === 'upload') {
          socket && socket.send(data.file)
        } else {
          socket && socket.send(JSON.stringify(data))
        }
        // socket.send(JSON.stringify(data))
      }, 500)
      break
    }
    default:
      break
  }
}

export const close = () => {
  socket.close()
}

export const getReadyState = () => {
  return socket.readyState
}

export default {
  init,
  send,
  close,
  getReadyState
}
